/**
 * Copyright(c) kyle.
 */
package org.example.metrics;

import com.codahale.metrics.*;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.ThreadLocalRandom.current;

/**
 * 自定义计数器，减少对应用程序性能侵入损耗
 *
 * @author kyle
 * @version 1.00.00
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2021-09-21 12:51]
 * @since [2021-09-21 12:51]
 */
public class CounterExample {
    public static final MetricRegistry registry = new MetricRegistry();
    public static final //定义运行的相关参数
            ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    public static final BlockingDeque<Long> queue = new LinkedBlockingDeque<>(1_00);

    public static void main(String[] args) {

        reporter.start(10, TimeUnit.SECONDS);
        Counter counter = registry.counter("queue-count",Counter::new);

        new Thread(()->{
            while (true){
                randomSleep();
                queue.add(System.nanoTime());
                counter.inc();
            }
        }).start();
        new Thread(()->{
            while (true){
                randomSleep();
                if(queue.poll()!=null){
                    counter.dec();
                }
            }
        }).start();
    }

    private static void randomSleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(current().nextInt(500));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
